import {
  Button, Modal, Tag, Form, Select, Input, Checkbox,
  Row, Col,
  message
} from 'antd'
import { http } from '@/utils'
import React, { useState, useImperativeHandle } from 'react'
import Signal from './Signal'

import { useStore } from '@/store'

const tagRender = (props) => {
  const { label, closable, onClose } = props
  const onPreventMouseDown = (event) => {
    event.preventDefault()
    event.stopPropagation()
  }
  return (
    <Tag
      onMouseDown={onPreventMouseDown}
      closable={closable}
      onClose={onClose}
      style={{
        marginRight: 3,
      }}
    >
      {label}
    </Tag>
  )
}

const Configmodal = (props) => {
  const [form] = Form.useForm()
  const [showModalOpen, setShowModalOpen] = useState(false)
  const [plainOptions, setPlainOptions] = useState([]) // 预警方法
  const [userOptions, setUserOptions] = useState([])// 用户列表
  const [freqListOpt, setFreqListOpt] = useState([]) // 周期列表
  const [factorListOpt, setFactorList] = useState([]) //因子列表
  const [tradeDirectionOpt, setTradeDirectionOpt] = useState([]) //预警周期
  const [signalList, setSignalList] = useState([]) // 信号列表
  const [fromData, setFromData] = useState({})

  const { loginStore } = useStore()

  const addConfigModalOpenOk = () => {
    setShowModalOpen(false)
  }
  const addConfigModalOpenCancel = () => {
    setShowModalOpen(false)
  }

  /**订阅信号 */
  let childRef = React.createRef()
  const showSignalModalOpen = (data) => {
    childRef.current.openModalOpen(data)
  }
  useImperativeHandle(props.onRef, () => {
    return {
      openModalOpen: openModalOpen,
    }
  })
  // 打开model 初始化
  const openModalOpen = async (data) => {
    form.resetFields()
    setFromData({
      ...data,
      groupId: data.id
    })
    setShowModalOpen(true)
    setPlainOptions(props.dictData['1002'].map(item => ({ label: item.dictName, value: item.dictCode })))
    setTradeDirectionOpt(props.dictData['1001'].map(item => ({ label: item.dictName, value: item.dictCode })))
    await getUserList()

    let tbAlarmConfigDetialList = []
    if (data.configId) {
      tbAlarmConfigDetialList = data.tbAlarmConfigDetialList.map((item, i) => {
        const factorList = item.factorId.split(',')
        const tradeDirection = item.tradeDirection.split(',')
        return {
          factorList: factorList.map(item => +item),
          freqList: +item.freqId,
          tradeDirection: tradeDirection.map(item => +item),
          key: i,
          id: i
        }
      })
      const userList = data.userList.split(',')
      const alarmMethodList = data.alarmMethodList.split(',')
      form.setFieldsValue({
        alarmMethodList: alarmMethodList.map(item => +item),
        userList: userList.map(item => +item),
        webhookList: data.webhookList,
      })
    }
    console.log(tbAlarmConfigDetialList)
    setSignalList(tbAlarmConfigDetialList)
  }
  // 订阅信号修改
  const changeConfigModal = (params) => {
    if (params) {
      let list = signalList.map(item => {
        if (item.key === params.key) {
          item = params
        }
        return item
      })
      if (!list.filter(item => item.key === params.key).length) {
        list = [
          ...list,
          {
            ...params,
            key: params.key ? params.key : new Date().getTime(),
            id: params.id ? params.id : null
          }
        ]
      }
      setSignalList(list)
    }
  }

  const formatFreqList = (data) => {
    const label = freqListOpt.filter(item => item.value === data)[0].label
    return `${label}`
  }
  const formatFactorList = (data) => {
    const list = factorListOpt.filter(item => data.indexOf(item.value) !== -1)
    return list.map((item, index) => (
      <span key={item.value}>{item.label}{index === list.length - 1 ? '' : ','}</span>
    ))
  }
  const formatTradeDirection = (data) => {
    const list = tradeDirectionOpt.filter(item => data.indexOf(item.value) !== -1)
    return list.map((item, index) => (
      <span key={item.value}>{item.label}{index === list.length - 1 ? '' : ','}</span>
    ))
  }
  const delTradeDirection = (data) => {
    const list = signalList.filter((item, index) => index !== data)
    setSignalList(list)
  }
  const addOrUpdataFinish = async (values) => {
    if (values.alarmMethodList.indexOf(2) !== -1 && !values.webhookList) {
      return message.warning('请输入钉钉群的群标识')
    }
    let tbAlarmConfigDetials = []
    if (signalList.length) {
      tbAlarmConfigDetials = signalList.map(item => {
        return {
          factorId: item.factorList.join(','),
          // factorId: item.factorList,
          freqId: item.freqList,
          tradeDirection: item.tradeDirection.join(','),
          id: item.id
        }
      })
    }
    const list = {
      alarmMethodList: values.alarmMethodList.map(item => {
        return { id: null, methodId: item }
      }),
      configId: fromData.configId || null,
      groupId: fromData.groupId,
      tbAlarmConfigDetials: tbAlarmConfigDetials,
      userId: loginStore.userId,
      userList: values.userList.map(item => {
        return { id: null, userId: item }
      }),
      webhookList: values.webhookList
    }
    console.log(list)
    const res = await http.post('/alarm/deliversign/addOrUpdateAlarmConfig', list)
    message.success(res.body)
    setShowModalOpen(false)
    props.changeConfig()
  }
  const getUserList = async () => {
    const res = await http.post('/alarm/deliversign/userList', {
      limit: 9999, pageCurrent: 1, userId: loginStore.userId,
      pageNum: 1,
      pageSize: 9999
    })
    console.log('用户列表-', res.body)
    const list = res.body.list.map(item => ({
      value: item.userId,
      label: item.username
    }))
    setUserOptions(list)
    form.setFieldsValue({
      userList: [+loginStore.userId],
    })
    await getFreq()
    await getFactor()
  }
  const getFreq = async () => {
    const res = await http.post('/alarm/deliversign/getAllFreqByType', {
      freqType: 1,
    })
    console.log('周期列表-', res.body)
    const list = res.body.map(item => ({
      value: item.id,
      label: item.freqName
    }))
    setFreqListOpt(list)
  }
  const getFactor = async () => {
    const res = await http.post('/alarm/deliversign/getAllFactor')
    console.log('因子列表-', res.body)
    const list = res.body.map(item => ({
      value: item.id,
      label: item.factorName
    }))
    setFactorList(list)
  }
  return (
    <>
      <Modal
        forceRender
        key={!showModalOpen ? Math.random() : '1'}
        title="添加预警组配置"
        open={showModalOpen}
        onOk={addConfigModalOpenOk}
        onCancel={addConfigModalOpenCancel}
        footer={false}
        width={800}
      >
        <Form
          form={form}
          onFinish={addOrUpdataFinish}
          colon={false}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          style={{
            marginTop: 30,
            minWidth: 500,
          }}
          initialValues={{
            alarmMethodList: [],
          }}
        >
          <Form.Item
            label="预警方法"
            name="alarmMethodList"
            rules={[
              { required: true, message: '请选择预警方法' }
            ]}
          >
            <Checkbox.Group options={plainOptions} />
          </Form.Item>
          <Form.Item
            label="预警对象"
            name="userList"
            rules={[
              {
                required: true,
                message: '请选择预警对象',
              }
            ]}
          >
            <Select
              mode="multiple"
              placeholder='请选择用户'
              showArrow
              disabled={+loginStore.userId !== 1}
              tagRender={tagRender}
              style={{ width: 350 }}
              filterOption={(input, option) =>
                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
              options={userOptions}
            />
          </Form.Item>
          <Form.Item label=" " name="webhookList" >
            <Input
              allowClear
              placeholder='请输入群标识'
              style={{ width: 350 }}
            />
          </Form.Item>
          <Form.Item label="订阅信号">
            <div>
              <div style={{ verticalAlign: 'top' }}>
                {signalList.map((item, index) => (
                  <Row
                    style={{ marginBottom: 5 }}
                    key={item.key}
                  >
                    <Col span={24} style={{}}>
                      <span>预警周期：{formatFreqList(item.freqList)}; </span>
                      <span>预警因子：</span>
                      <span>{formatFactorList(item.factorList)}; </span>
                      <span>交易方向：</span>
                      <span>{formatTradeDirection(item.tradeDirection)};</span>
                      <Button style={{ padding: '0 5px 0 10px', height: 25 }} onClick={() => showSignalModalOpen(item)} type="link">编辑</Button>
                      <Button style={{ padding: '0 5px', height: 25 }} onClick={() => delTradeDirection(index)} type="link">删除</Button>
                    </Col>
                  </Row>
                ))}
              </div>
              <Button size='small' onClick={() => showSignalModalOpen()}>添加</Button>
            </div>
          </Form.Item>
          <Form.Item label=" " style={{ margin: 0 }}>
            <div style={{ textAlign: 'right' }}>
              <Button htmlType="submit" type="primary">
                提交
              </Button>
            </div>
          </Form.Item>
        </Form>
      </Modal>
      <Signal
        onRef={childRef}
        changeConfigModal={changeConfigModal}
        tradeDirectionOpt={tradeDirectionOpt}
        freqListOpt={freqListOpt}
        factorListOpt={factorListOpt}
      ></Signal>
    </>
  )
}
export default Configmodal
